"""
日志路由模块
定义日志流相关的API路由
"""

from flask import Blueprint, Response, jsonify, request
import threading
import time  # 添加time模块导入
from app.logs_server.service import (
    get_log_generator_status, 
    set_log_generator_status, 
    get_log_generator_thread, 
    set_log_generator_thread,
    log_generator
)

logs_bp = Blueprint('logs_server', __name__)

@logs_bp.route('/logs/stream')
def stream_logs():
    """
    SSE日志流端点
    通过HTTP流持续向客户端推送日志数据
    客户端可以使用EventSource API连接到此端点
    """
    def generate():
        """
        生成器函数，持续产生SSE格式的数据
        """
        # SSE需要特定的响应头
        yield "retry: 5000\n\n"  # 设置重连时间间隔为5秒
        
        # 持续生成日志数据
        while True:
            # 检查日志生成器是否正在运行
            if get_log_generator_status():
                # 从日志生成器获取下一个日志条目
                try:
                    entry = next(log_generator())
                    yield entry
                except StopIteration:
                    # 如果生成器停止，发送空数据保持连接
                    yield "data: {}\n\n"
            else:
                # 如果生成器未运行，发送心跳保持连接
                yield ": heartbeat\n\n"
            # 短暂休眠以避免过度占用CPU
            time.sleep(0.1)

    # 返回SSE响应，指定正确的MIME类型
    return Response(
        generate(),
        mimetype="text/event-stream",  # SSE标准MIME类型
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Access-Control-Allow-Origin": "*"  # 允许跨域访问
        }
    )

@logs_bp.route('/logs/start', methods=['POST'])
def start_stream():
    """
    启动日志流生成器
    """
    # 如果日志生成器已经在运行，返回相应信息
    if get_log_generator_status():
        return jsonify({
            "status": "already_running",
            "message": "日志流生成器已在运行"
        })
    
    # 启动日志生成器
    set_log_generator_status(True)
    thread = threading.Thread(target=log_generator)
    thread.daemon = True
    set_log_generator_thread(thread)
    thread.start()
    
    return jsonify({
        "status": "started",
        "message": "日志流生成器已启动"
    })

@logs_bp.route('/logs/stop', methods=['POST'])
def stop_stream():
    """
    停止日志流生成器
    """
    # 如果日志生成器未在运行，返回相应信息
    if not get_log_generator_status():
        return jsonify({
            "status": "not_running",
            "message": "日志流生成器未在运行"
        })
    
    # 停止日志生成器
    set_log_generator_status(False)
    
    return jsonify({
        "status": "stopped",
        "message": "日志流生成器已停止"
    })

@logs_bp.route('/logs/status')
def stream_status():
    """
    获取日志流状态
    """
    running = get_log_generator_status()
    return jsonify({
        "running": running,
        "message": "日志流生成器正在运行" if running else "日志流生成器未运行"
    })
